import React from 'react'
import { connect } from 'react-redux'
import {messages} from "share/common";
import {Button, Form, Input, Select, Switch,message} from 'antd';
import Chooser from 'components/chooser';
import costCenterGroupService from 'containers/setting/cost-center-group/cost-center-group.service';
import 'styles/setting/cost-center-group/edit-cost-center-group.scss';
const FormItem = Form.Item;

class EditCostCenterGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      record: this.props.params.record,
    }
  }

  //获取数据
  componentWillMount() {
    this.props.form.setFieldsValue(this.state.record)
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.params.show !== this.props.params.show) {
      this.setState({
        record: nextProps.params.record,
      }, () => {
         if(nextProps.params.record.hasOwnProperty("description")){
           this.props.form.setFieldsValue(nextProps.params.record)
         }else{
           let item = Object.assign({description: ""}, nextProps.params.record)
           this.props.form.setFieldsValue(item)
         }
      });
    }
  }


  //点击确认
  handleSave = (e) => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        let  params = Object.assign(JSON.parse(JSON.stringify(record)), values);
        if(!params.costCenterGroupCategoryId){
          message.warning(messages('setting.key1666')/*请选择成本中心组类别*/)
          return;
        }else{
          this.setState({
            loading: true
          });
          if(params.id){
            costCenterGroupService.editCostCenterGroup(params).then(res => {
                this.setState({
                  loading: false
                });
                this.props.close(true);
              }
            ).catch(err => {
              this.setState({
                loading: false,
              })
            })
          }else{
            costCenterGroupService.addCostCenterGroup(params).then(res => {
                this.setState({
                  loading: false
                });
                this.props.close(true);
              }
            ).catch(err => {
              this.setState({
                loading: false,
              });
            })
          }
        }
      }
    })
  };

  onCancel = () => {
    this.props.close();
  };
  costCenterGroupCategoryChange = (e) => {
    let costCenterGroupCategory = {}
    let record = this.state.record;
    if (e.length > 0) {
      costCenterGroupCategory = e[0];
      record.costCenterGroupCategoryId = costCenterGroupCategory.id;
      record.costCenterGroupCategoryName = costCenterGroupCategory.name;
      record.setOfBooksId = costCenterGroupCategory.setOfBooksId;
      this.setState({
        record
      },()=>{
      })
    }
  }
  renderCostCenterGroupCategoryName = (record) => {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: { span:8 },
      wrapperCol: { span:15 }
    };

    if(record.id){
      return (
        <FormItem label={messages('setting.key1664')/*成本中心组类别*/} {...formItemLayout}>
          {getFieldDecorator('costCenterGroupCategory',{
            initialValue: record.costCenterGroupCategoryName,
          })
          (<Input value={record.costCenterGroupCategoryName} disabled={true}/>)
          }
        </FormItem>
      )
    }else {
      return (
        <FormItem label={
            <span>
                <span className="required-red">*&nbsp;</span>
                <span>{messages('setting.key1664')/*成本中心组类别*/}</span>
            </span>
          }
          {...formItemLayout}>
            <div>
              <Chooser single={true}
                       value={record.costCenterGroupCategoryName ? [
                         {
                           name: record.costCenterGroupCategoryName,
                           id: record.costCenterGroupCategoryId,
                           setOfBooksId:record.setOfBooksId
                         }
                       ] : []}
                       showClear={false}
                       type="cost_center_group_class"
                       placeholder={messages("common.please.select")}
                       labelKey="name"
                       onChange={this.costCenterGroupCategoryChange}
                       valueKey="id"
                       listExtraParams={{enabled:true}}/>
            </div>
          <span style={{color: 'gray'}}> {messages('setting.key1667')/*成本中心组类别选择保存后不可修改*/}
            </span>
        </FormItem>
      )
    }
  }
  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, record} = this.state;
    const formItemLayout = {
      labelCol: { span:8 },
      wrapperCol: { span:15 }
    };
    return (
      <div className='edit-cost-center-group'>
        <Form>
          <FormItem label={messages('common.column.status')/*状态*/} {...formItemLayout}>
            {getFieldDecorator('enabled',{
              valuePropName: "checked",
            })
            (<Switch/>)
            }
          </FormItem>
          {this.renderCostCenterGroupCategoryName(record)}
          <FormItem label={messages('setting.key369'/*成本中心组代码*/)} {...formItemLayout}>
            {getFieldDecorator('costCenterGroupCode',{
              rules: [{
                required: true,
                message: messages('setting.key392'/*成本中心组代码不能为空*/)
              }]
            })
            (<Input disabled={!!record.costCenterGroupCode}/>)
            }
            <span style={{color: 'gray'}}>
              {messages('setting.key395'/*注：成本中心组代码保存后不可修改*/)}
            </span>
          </FormItem>
          <FormItem label={messages('setting.key370'/*成本中心组名称*/)} {...formItemLayout}>
            {getFieldDecorator('costCenterGroupName',{
              rules: [{
                required: true,
                message: messages('setting.key393'/*成本中心组名称不能为空*/)
              }]
            })
            (<Input />)
            }
          </FormItem>

          <FormItem label={messages('setting.key199'/*描述*/)} {...formItemLayout}>
            {getFieldDecorator('description',{
              rules:[
                {
                  required: false,
                },
                {
                  validator: (item, value, callback)=>{
                    value && value.length > 149 && message.warning(messages('setting.key1522')/*最多输入150个字符*/);
                    callback();
                  }
                }
              ],
            })
            (<Input maxLength={"150"}/>)
            }
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" onClick={this.handleSave} loading={loading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
      </div>
    )
  }

}

EditCostCenterGroup.contextTypes = {
  router: React.PropTypes.object,
};
function mapStateToProps(state) {
  return {
  }
}

const wrappedEditCostCenterGroup = Form.create()(EditCostCenterGroup);
export default connect(mapStateToProps)(wrappedEditCostCenterGroup);
